/**
 * AI聊天服务
 */

import { BaseApiService, TableDataInfo, API_CONFIG, AuthManager } from '../utils/api';
import {
	AiChatRequestDto,
	AiChatResponseDto,
	ChatMessageVo,
} from '../types/api';

export interface ChatHistoryParams {
	pageNum?: number;
	pageSize?: number;
	sessionId?: number;
}
export interface ChatHistoryTimeRangeParams {
	pageNum?: number;
	pageSize?: number;
	start?: string;
	end?: string;
	sessionId?: number;

}

export class AiChatService extends BaseApiService {

	/**
	 * 发送AI聊天消息 - 使用更长的超时时间
	 */
	async sendMessage(data: AiChatRequestDto): Promise<AiChatResponseDto> {
		// 获取认证头
		const authHeaders = await this.getAuthHeaders();

		// 创建兼容的超时控制器
		const controller = new AbortController();
		const timeoutId = setTimeout(() => {
			controller.abort();
		}, API_CONFIG.AI_CHAT_TIMEOUT);

		try {
			// 使用60秒超时时间
			const response = await fetch(`${API_CONFIG.BASE_URL}/api/ai-chat/send`, {
				method: 'POST',
				headers: {
					...API_CONFIG.HEADERS,
					...authHeaders,
				},
				body: JSON.stringify(data),
				signal: controller.signal,
			});

			clearTimeout(timeoutId);

			if (!response.ok) {
				throw new Error(`HTTP ${response.status}: ${response.statusText}`);
			}

			const result = await response.json();
			console.log('AI聊天原始响应:', result);

			// 检查响应格式，可能是包装在R对象中的
			if (result.data) {
				return result.data;
			}

			return result;
		} catch (error) {
			clearTimeout(timeoutId);
			throw error;
		}
	}

	// 获取认证头
	private async getAuthHeaders(): Promise<Record<string, string>> {
		const token = await AuthManager.getToken();
		return token ? { Authorization: `Bearer ${token}` } : {};
	}

	/**
	 * 分页查询当前用户的聊天记录
	 */
	async getChatHistory(params: ChatHistoryParams = {}): Promise<TableDataInfo<ChatMessageVo>> {
		// 获取认证头
		const authHeaders = await this.getAuthHeaders();

		// 创建兼容的超时控制器
		const controller = new AbortController();
		const timeoutId = setTimeout(() => {
			controller.abort();
		}, API_CONFIG.AI_CHAT_TIMEOUT);

		try {
			const { pageNum = 1, pageSize = 10, sessionId } = params;

			const response = await fetch(`${API_CONFIG.BASE_URL}/api/chat/history?pageNum=${pageNum}&pageSize=${pageSize}${sessionId ? `&sessionId=${sessionId}` : ''}`, {
				method: 'GET',
				headers: {
					...API_CONFIG.HEADERS,
					...authHeaders,
				},
				signal: controller.signal,
			});

			clearTimeout(timeoutId);

			if (!response.ok) {
				throw new Error(`HTTP ${response.status}: ${response.statusText}`);
			}

			const result = await response.json();
			return result;
		} catch (error) {
			clearTimeout(timeoutId);
			throw error;
		}
	}

	/**
	 * 分页查询当前用户的聊天记录
	 */
	async getHistoryByTimeRange(params: ChatHistoryTimeRangeParams = {}): Promise<TableDataInfo<ChatMessageVo>> {
		// 获取认证头
		const authHeaders = await this.getAuthHeaders();

		// 创建兼容的超时控制器
		const controller = new AbortController();
		const timeoutId = setTimeout(() => {
			controller.abort();
		}, API_CONFIG.AI_CHAT_TIMEOUT);

		try {
			const { pageNum = 1, pageSize = 99999, start, end, sessionId } = params;

			// 构建查询参数
			const queryParams = new URLSearchParams({
				pageNum: pageNum.toString(),
				pageSize: pageSize.toString(),
				start: start?.toString() || '',
				end: end?.toString() || '',
			});
			if (sessionId) queryParams.append('sessionId', sessionId.toString());

			const response = await fetch(`${API_CONFIG.BASE_URL}/api/chat/history/byTime?${queryParams.toString()}`, {
				method: 'GET',
				headers: {
					...API_CONFIG.HEADERS,
					...authHeaders,
				},
				signal: controller.signal,
			});

			clearTimeout(timeoutId);

			if (!response.ok) {
				throw new Error(`HTTP ${response.status}: ${response.statusText}`);
			}

			const result = await response.json();
			return result.data;
		} catch (error) {
			clearTimeout(timeoutId);
			throw error;
		}
	}
}

// 导出单例实例
export const aiChatService = new AiChatService();
